<!--
 * @Date: 2025-02-25 14:51:45
 * @LastEditTime: 2025-03-27 15:49:50
 * @FilePath: \LeagueBard\frontend\src\components\historyRecord\detailDialog.vue
 * @Description: 战绩详情页
-->
<script lang="ts" setup>
import type { MatchDetailData } from './types'
import { getMatchDetailApi } from '@/api/client/matchApi'
import LcuImage from '@/components/lcuImage.vue'
import { gameAssetManager } from '@/LcuApi/gameAsset'
import router from '@/router'
import dayjs from 'dayjs';
import { defineEmits, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';

// 图标引入
import detailInfoRow from './detailInfoRow.vue';

const { t } = useI18n()

// 颜色
const colors = ref(['#3399FF', '#FF6B6B', '#E8E8E8', '#3D3D3D', '#D4C4A8', '#A89BB7', '#D4AF37', '#7FC7C1'])

const visible = ref(false)
const loading = ref(false)
const matchDetail = ref<MatchDetailData>({})
async function init({ gameId, win }) {
  visible.value = true
  loading.value = true
  const matchData: any = await getMatchDetailApi(gameId)
  if (!matchData) {
    loading.value = false
    return
  }

  // 合并参与者身份与详细信息
  const participantsWithIdentity = (matchData.participantIdentities || []).map(identity => ({
    ...identity,
    ...(matchData.participants?.find(p => p.participantId === identity.participantId) || {}),
  }))

  const championInfos = await gameAssetManager.getChampionInfo(participantsWithIdentity.map(item => item.championId))
  // 按队伍分组
  const groupedTeams = []
  participantsWithIdentity.forEach(participant => {
    const teamId = participant.teamId
    participant.championInfo = championInfos.find(item => item.id === participant.championId)

    let team = groupedTeams.find(t => t.teamId === teamId)
    // 计算队伍击杀、助攻、死亡、金钱
    const { kills, deaths, assists, goldEarned } = participant?.stats ?? {}
    if (!team) {
      team = { teamId, members: [], teamKills: 0, teamAssists: 0, teamDeaths: 0, teamGoldEarned: 0 };
      groupedTeams.push(team);
    }
    // 添加到队伍
    team.members.push(participant);
    team.teamKills += kills
    team.teamDeaths += deaths
    team.teamAssists += assists
    team.teamGoldEarned += goldEarned
  })
  groupedTeams.forEach((item, index) => {
    const team = matchData.teams.find(i => i.teamId === item.teamId)
    if (team) {
      groupedTeams[index] = { ...item, ...team }
    }
  })

  // 整合数据
  matchDetail.value = {
    gameId: matchData.gameId,
    mapId: matchData.mapId,
    queueId: matchData.queueId,
    queueInfo: await gameAssetManager.getGameQueueInfo(matchData.queueId),
    win,
    gameDuration: dayjs(matchData.gameDuration * 1000).format('mm:ss'),
    gameCreation: dayjs(matchData.gameCreation).format('YYYY-MM-DD HH:mm:ss'),
    gameType: matchData.gameType,
    gameMode: matchData.gameMode,
    gameTeam: groupedTeams,
  }
  loading.value = false
  // console.log('matchDetail.value', matchDetail.value);
}
const addPlayer = inject('addPlayer')
function viewPlayer(puuid) {
  if (!puuid) return
  // 检查 addPlayer 是否为可调用函数
  closeDialog()
  if (typeof addPlayer === 'function') {
    addPlayer(puuid)
  } else {
    router.push({ path: '/', query: { puuid } })
    // console.error('addPlayer 不是一个可调用的函数');
  }
}

// 关闭弹窗
function closeDialog() {
  visible.value = false
}

// 暴露方法
defineExpose({ init })
</script>

<template>
  <a-drawer width="67%" :visible="visible" placement="left" body-class="history_record_detail" unmount-on-close
    :footer="false" :header="false" @cancel="closeDialog">
    <div class="detail_header flex items-center px-20px py-10px">
      <!-- 模式地图 -->
      <div class="w-45px h-45px">
        <LcuImage :id="matchDetail.mapId" width="100%" height="100%" radius="0" type="map" />
      </div>
      <div class="detail_header_info">
        <p v-if="matchDetail.win" class="isWin text-30px font-900">{{ t(`HistoryRecord.win`) }}</p>
        <p v-else class="isLose text-30px font-900">{{ t(`HistoryRecord.lose`) }}</p>
      </div>
      <div class="detail_header_info">
        <p class="text-12px opacity-50">{{ t(`HistoryRecord.mode`) }}</p>
        <p class="text-14px font-bold">{{ matchDetail.queueInfo?.detailedDescription || matchDetail?.queueInfo?.name }}</p>
      </div>
      <div class="detail_header_info">
        <p class="text-12px opacity-50">{{ t(`HistoryRecord.gameDuration`) }}</p>
        <p class="text-14px font-bold">{{ matchDetail.gameDuration }}</p>
      </div>
      <div class="detail_header_info">
        <p class="text-12px opacity-50">{{ t(`HistoryRecord.gameCreation`) }}</p>
        <p class="text-14px font-bold">{{ matchDetail.gameCreation }}</p>
      </div>
      <div class="detail_header_info">
        <p class="text-12px opacity-50">{{ t(`HistoryRecord.gameId`) }}</p>
        <p class="text-14px font-bold">{{ matchDetail.gameId }}</p>
      </div>
    </div>
    <div class="detail_main py-10px px-16px">
      <div v-for="(item, index) in matchDetail.gameTeam" :key="item.teamId" class="mt-5px mb-10px">
        <!-- 队伍总览 -->
        <a-row class="team_overview flex items-center justify-between mb-5px">
          <a-col :span="16" class="team_info flex items-center">
            <div class="team_name" :style="{ color: colors[index] }">{{ t(`Teams.${index + 1}`) }}</div>
            <div class="info_point"></div>
            <div class="team_stats">
              <icon-pushpin />
              <span>{{ item.teamKills }}/{{ item.teamDeaths }}/{{ item.teamAssists }}</span>
            </div>
            <div class="info_point"></div>
            <div class="team_money">
              <icon-copyright />
              <span>{{ item.teamGoldEarned }}</span>
            </div>
          </a-col>
          <a-col v-if="index === 0" :span="8" class="data_switch flex items-center">
            <a-col :span="8" class="item_icon_stats">
              <icon-pushpin />
            </a-col>
            <a-col :span="8" class="item_icon_data">
              <icon-thunderbolt />
            </a-col>
            <a-col :span="8" class="item_icon_gold">
              <icon-copyright />
            </a-col>
          </a-col>
        </a-row>
        <!-- 每个成员的信息 -->
        <detailInfoRow v-for="member, i in item.members" :key="i" :data="member" :color="colors[index]" @view-player="viewPlayer" />
      </div>
    </div>
  </a-drawer>
</template>

<style lang="scss">
.history_record_detail {
  width: 100%;
  height: 100%;
  padding: 0;
  display: flex;
  flex-direction: column;

  .detail_header {
    border-bottom: 1px solid #D9D9D9;

    .detail_header_info {
      padding-left: 15px;

      &+.detail_header_info {
        margin-left: 20px;
        border-left: 1px solid #D9D9D9;
      }
    }
  }

  .detail_main {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }

  .team_overview {
    width: 100%;
    color: #989E8B;

    .team_name {
      font-size: 16px;
      font-weight: bold;
    }

    .team_stats,
    .team_money {
      display: flex;
      align-items: center;
      font-size: 14px;
      font-weight: bold;

      span {
        margin-left: 5px;
      }
    }

    .info_point {
      &::after {
        content: '·';
        font-size: 20px;
        margin: 0 14px;
        line-height: 1;
      }
    }

    .data_switch {
      width: 38%;
      height: 100%;

      .item_icon_stats,
      .item_icon_data,
      .item_icon_gold {
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        overflow: hidden;
      }
    }
  }

  .detail_info_row {
    border-bottom: 1px solid transparent;
    border-top: 1px solid transparent;

    &+.detail_info_row {
      border-top: none;
    }
  }
}
</style>
